package cn.openea.perpartner.meily.web.controller;

import cn.hutool.json.JSONUtil;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.poi.ExcelUtil;
import cn.openea.perpartner.common.core.web.controller.BaseController;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TableDataInfo;
import cn.openea.perpartner.meily.web.entity.GroupBuyingSub;
import cn.openea.perpartner.meily.web.entity.dto.GoodsSalesDataDTO;
import cn.openea.perpartner.meily.web.entity.dto.GroupBuyingSubDTOFactory;
import cn.openea.perpartner.meily.web.entity.dto.GroupBuyingSubDTOFactory.*;
import cn.openea.perpartner.meily.web.entity.dto.GroupBuyingSubDTOFactory.ExportExcelTemplateDto;
import cn.openea.perpartner.meily.web.entity.dto.GroupBuyingSubDTOFactory.ShipmentTemplateDTO;
import cn.openea.perpartner.meily.web.entity.vo.OrderAddressVo;
import cn.openea.perpartner.meily.web.entity.vo.OrderRecordBatchVo;
import cn.openea.perpartner.meily.web.entity.vo.OrderRecordVo;
import cn.openea.perpartner.meily.web.entity.vo.OrderSalesDataVo;
import cn.openea.perpartner.meily.web.service.IGroupBuyingSubService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author ysk
 * @version 1.0.1
 * @Description 交易管理
 * @createTime 2023年04月18日 15:45:00
 */
@Api(tags = "后台交易管理")
@RestController
@RequestMapping("/trade")
public class TradeController extends BaseController {

    @Resource
    private IGroupBuyingSubService groupBuyingSubService;
    @Resource
    private GroupBuyingSubDTOFactory groupBuyingSubDTOFactory;

    @ApiOperation("订单分页查询")
    @GetMapping("/order/record/page/list")
    public AjaxResult orderRecordList(OrderRecordVo recordVo) {
        startPage();
        List<GroupBuyingSub> groupBuyingSubs = groupBuyingSubService.selectList(recordVo);
        TableDataInfo dataTable = getDataTable(groupBuyingSubs);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", groupBuyingSubs
                .parallelStream()
                .map(item -> groupBuyingSubDTOFactory.toDetailsDto.apply(item))
                .collect(Collectors.toList()));
        jsonObject.put("total", dataTable.getTotal());
        if (StringUtils.isBlank(recordVo.getOrderStatus())) {
            Map<String, Integer> map = groupBuyingSubService.orderStatusCountQuery(recordVo);
            jsonObject.put("orderStatusCount", map);
        }
        return AjaxResult.success(jsonObject);
    }

    @ApiOperation("订单更改收货地址")
    @PostMapping("/order/change/address")
    public AjaxResult orderChangeAddress(@RequestBody @Valid OrderAddressVo orderAddressVo) {
        GroupBuyingSub groupBuyingSub = Optional.ofNullable(groupBuyingSubService.getById(orderAddressVo.getId()))
                .orElseThrow(() -> new ServiceException("订单不存在"));
        String address = groupBuyingSub.getAddress();
        if (!JSONUtil.isJson(address)) {
            return AjaxResult.error("数据异常，请联系系统管理进行修复");
        }
        JSONObject jsonObject = JSONObject.parseObject(address);
        jsonObject.put("Region", orderAddressVo.getRegion());
        jsonObject.put("Address", orderAddressVo.getAddress());
        jsonObject.put("StreetVillage", orderAddressVo.getStreetVillage());
        jsonObject.put("Name", orderAddressVo.getName());
        jsonObject.put("PhoneNum", orderAddressVo.getPhoneNum());
        jsonObject.put("InfoChange", true);
        groupBuyingSubService.orderChangeAddress(groupBuyingSub.getId(), JSONObject.toJSONString(jsonObject));
        return AjaxResult.success();
    }

    @ApiOperation("订单延迟收货")
    @PostMapping("/order/delayed/receipt/{id}/{days}")
    public AjaxResult orderDelayedReceipt(@PathVariable String id, @PathVariable Integer days) {
        groupBuyingSubService.orderDelayedReceipt(id, days);
        return AjaxResult.success();
    }

    @ApiOperation("导出订单信息")
    @PostMapping("/order/export/excel")
    public void orderExportExcel(@RequestBody OrderRecordBatchVo batchVo, HttpServletResponse response) {
        List<GroupBuyingSub> groupBuyingSubs;
        if (batchVo.byIds()) {
            // 根据id去查
            groupBuyingSubs = groupBuyingSubService.selectByIds(batchVo.getBatchIds());
        } else {
            groupBuyingSubs = groupBuyingSubService.selectList(batchVo.getQueryVO());
        }
        List<ExportExcelTemplateDto> exportExcelTemplateDtos = groupBuyingSubs
                .parallelStream()
                .map(item -> groupBuyingSubDTOFactory.toExportExcelTemplateDto.apply(item))
                .collect(Collectors.toList());
        // 导出
        ExcelUtil<ExportExcelTemplateDto> util = new ExcelUtil<>(ExportExcelTemplateDto.class);
        util.exportExcel(response, exportExcelTemplateDtos, "订单记录列表.xlsx");
    }

    @ApiOperation("商品销售情况")
    @GetMapping("/sales/good/page/list")
    public AjaxResult goodsSalesPageList(OrderSalesDataVo salesDataVo) {
        startPage();
        List<GoodsSalesDataDTO> goodsSalesDataDTOS = groupBuyingSubService.salesStatisticsList(salesDataVo);
        TableDataInfo dataTable = getDataTable(goodsSalesDataDTOS);
        Map<String, Object> data = new HashMap<>();
        data.put("list", dataTable.getRows());
        data.put("total", dataTable.getTotal());
        data.put("allGoodsSalesData", groupBuyingSubService.statisticsAllGoodsSalesData(salesDataVo));
        return AjaxResult.success(data);
    }


    @ApiOperation("导出订单销售数据")
    @PostMapping("/export/goods/sales/data")
    public void exportGoodsSalesData(@RequestBody OrderSalesDataVo salesDataVo, HttpServletResponse response) {
        // 全量导出
        List<GoodsSalesDataDTO> goodsSalesDataDTOS = groupBuyingSubService.salesStatisticsList(salesDataVo);
        ExcelUtil<GoodsSalesDataDTO> util = new ExcelUtil<>(GoodsSalesDataDTO.class);
        util.exportExcel(response, goodsSalesDataDTOS, "订单销售数据.xlsx");
    }

    @ApiOperation("订单物流情况分页查询")
    @GetMapping("/order/logistics/page/list")
    public AjaxResult orderLogisticsPageList(OrderRecordVo recordVo) {
        startPage();
        List<GroupBuyingSub> groupBuyingSubs;
        if (recordVo.isFortyEighthourData()) {
            groupBuyingSubs = groupBuyingSubService.findFortyEightHourData(recordVo);
        } else {
            groupBuyingSubs = groupBuyingSubService.selectList(recordVo);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("list", groupBuyingSubs
                .stream()
                .map(item -> groupBuyingSubDTOFactory.toDetailsDto.apply(item))
                .collect(Collectors.toList()));
        TableDataInfo dataTable = getDataTable(groupBuyingSubs);
        data.put("total", dataTable.getTotal());
        if (recordVo.isAllStatistics()) {
            Map<String, Integer> map = groupBuyingSubService.orderStatusCountQuery(recordVo);
            // 查询48小时收货数据的数量
            map.put("FORTYEIGHT_HOUR_RECEIVING_DATA", groupBuyingSubService.findFortyEightHourData(recordVo).size());
            data.put("orderStatusCount", map);
        }
        return AjaxResult.success(data);
    }

}
